package cn.rkylin.oms.warehouse.local.returnStockin.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.github.pagehelper.PageInfo;

import cn.rkylin.core.service.ApolloService;
import cn.rkylin.oms.aftersale.sysreturn.domain.SysReturnSku;
import cn.rkylin.oms.aftersale.sysreturn.service.ISysReturnService;
import cn.rkylin.oms.aftersale.sysreturn.vo.SysReturnVO;
import cn.rkylin.oms.common.consts.YesNoConst;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.goods.domain.GoodsSku;
import cn.rkylin.oms.goods.service.IGoodsService;
import cn.rkylin.oms.goodscost.vo.GoodsCostVO;
import cn.rkylin.oms.warehouse.extAdjust.service.AdjustSkuService;
import cn.rkylin.oms.warehouse.local.returnStockin.dao.ReturnStockinDAO;
import cn.rkylin.oms.warehouse.local.returnStockin.dao.ReturnStockinSkuDAO;
import cn.rkylin.oms.warehouse.local.returnStockin.domain.ReturnStockin;
import cn.rkylin.oms.warehouse.local.returnStockin.domain.ReturnStockinSku;
import cn.rkylin.oms.warehouse.local.returnStockin.vo.ReturnStockinSkuVO;
import cn.rkylin.oms.warehouse.local.returnStockin.vo.ReturnStockinVO;
import cn.rkylin.oms.warehouse.stock.service.IStockService;
import cn.rkylin.oms.warehouse.stock.vo.StockVO;

/**
 * 退货入库单Service
 * 
 * @author 齐涛
 * @version 1.0
 * @created 28-9-2017 10:51:30
 */
@Repository(value = "localReturnStockinService")
public class ReturnStockinServiceImpl extends ApolloService implements IReturnStockinService {

	@Value("${job.address}")
	private String jobAddress;

	@Autowired
	private ReturnStockinDAO returnStockinDAOImpl;

	@Autowired
	private ReturnStockinSkuDAO returnStockinSkuDAOImpl;

	@Autowired
	private ISysReturnService sysReturnService;

	@Autowired
	private IStockService stockService;

	@Autowired
	private AdjustSkuService adjustSkuService;

	@Autowired
	IGoodsService goodsServiceImpl;

	/**
	 * 查询退货入库单列表
	 * 
	 * @param page
	 *            页号
	 * @param rows
	 *            页大小
	 * @param returnStockinVO
	 *            退货入库单VO
	 * @return 退货入库单列表
	 * @throws Exception
	 *             异常
	 */
	@SuppressWarnings("rawtypes")
	public PageInfo findByWhere(int page, int rows, ReturnStockinVO returnStockinVO) throws Exception {
		PageInfo<ReturnStockinVO> returnStockinVOList = findPage(page, rows, "pageSelectLocalReturnStockin",
				returnStockinVO);
		return returnStockinVOList;
	}

	/**
	 * 查询退货入库单信息
	 *
	 * @param returnStockinVO
	 *            退货入库单VO
	 * @return 退货入库单信息
	 * @throws Exception
	 *             异常
	 */
	public ReturnStockinVO getReturnStockinInfo(ReturnStockinVO returnStockinVO) throws Exception {
		ReturnStockinVO data = returnStockinDAOImpl.getReturnStockinInfo(returnStockinVO);

		ReturnStockinSkuVO returnStockinSkuVO = new ReturnStockinSkuVO();
		returnStockinSkuVO.setStockinId(returnStockinVO.getStockinId());
		returnStockinSkuVO.setKind("plan");
		returnStockinSkuVO.setOrderBy("goods_code, sku_code");
		List<ReturnStockinSkuVO> skuDataList = returnStockinSkuDAOImpl.selectReturnStockinSkuList(returnStockinSkuVO);
		data.setReturnStockinSkuVOList(skuDataList);

		return data;
	}

	/**
	 * 查询退货入库单商品列表
	 *
	 * @param returnStockinSkuVO
	 *            退货入库单商品VO
	 * @return 退货入库单商品信息
	 * @throws Exception
	 *             异常
	 */
	public List<ReturnStockinSkuVO> selectReturnStockinSkuList(ReturnStockinSkuVO returnStockinSkuVO) throws Exception {
		return returnStockinSkuDAOImpl.selectReturnStockinSkuList(returnStockinSkuVO);
	}

	/**
	 * 修改退货入库单
	 * 
	 * @param returnStockinVO
	 *            退货入库单VO
	 * @return 更新条数
	 * @throws Exception
	 *             异常
	 */
	public int updateReturnStockin(ReturnStockinVO returnStockinVO) throws Exception {
		ReturnStockin returnStockin = new ReturnStockin();
		BeanUtils.copyProperties(returnStockinVO, returnStockin);
		return returnStockinDAOImpl.updateReturnStockin(returnStockin);
	}

	/**
	 * 取消退货入库单
	 *
	 * @param stockinId
	 *            退货入库单Id
	 * @throws Exception
	 *             异常
	 * @return 取消结果信息
	 */
	public Map<String, String> cancelReturnStockin(String stockinId) throws Exception {
		Map<String, String> returnMap = new HashMap<String, String>();

		ReturnStockinVO returnStockinVO = new ReturnStockinVO();
		returnStockinVO.setStockinId(stockinId);
		ReturnStockinVO returnStockinData = this.getReturnStockinInfo(returnStockinVO);

		ReturnStockinVO returnStockinInfo = new ReturnStockinVO();
		returnStockinInfo.setStockinId(returnStockinData.getStockinId());
		returnStockinInfo.setCancelStatus(YesNoConst.YES);
		this.updateReturnStockin(returnStockinInfo);

		// 更新退货单状态为待审核
		SysReturnVO sysReturnVO = new SysReturnVO();
		sysReturnVO.setReturnId(returnStockinData.getSourceId());
		sysReturnVO.setReturnStatus("a");
		sysReturnService.updateSysReturn(sysReturnVO);

		returnMap.put("success", "true");

		return returnMap;
	}

	/**
	 * 完成入库单
	 *
	 * @param stockInVO
	 *            入库单VO
	 * @return 完成入库单条数
	 * @throws Exception
	 *             异常
	 */
	@SuppressWarnings("rawtypes")
	public int updateFinishStockIn(ReturnStockinVO returnStockinVO) throws Exception {
		CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
		Iterator iterator = currentUser.getEnterpriseMap().keySet().iterator();
		String entId = (String) iterator.next();

		// 更新入库单
		returnStockinVO.setFinishTime(new Date());
		ReturnStockin returnStockin = new ReturnStockin();
		BeanUtils.copyProperties(returnStockinVO, returnStockin);
		int updateCount = returnStockinDAOImpl.updateReturnStockin(returnStockin);

		// 更新退货单状态为已完成
		SysReturnVO sysReturnVO = new SysReturnVO();
		sysReturnVO.setReturnId(returnStockinVO.getSourceId());
		sysReturnVO.setReturnStatus("z");
		sysReturnVO.setFactInTime(returnStockinVO.getFactInTime());
		sysReturnVO.setFinishType(returnStockinVO.getFinishType());
		sysReturnVO.setFinishTime(new Date());
		sysReturnService.updateSysReturn(sysReturnVO);

		List<ReturnStockinSkuVO> list = returnStockinVO.getReturnStockinSkuVOList();
		for (int i = 0; i < list.size(); i++) {
			ReturnStockinSkuVO returnStockinSkuVO = list.get(i);
			List<SysReturnSku> sysReturnSku = sysReturnService
					.findSysReturnSkuByReturnSkuId(returnStockinSkuVO.getSourceSkuId());

			// 添加实际入库单商品
			// 退货单上的非单据商品，取即时成本价
			if ("n".equals(sysReturnSku.get(0).getIsOrderSku())) {
				GoodsSku goodsSku = goodsServiceImpl.getGoodsSkuBySkuId(returnStockinSkuVO.getSkuId());
				returnStockinSkuVO.setGoodsSkuCost(goodsSku.getCostPrice());
			}
			ReturnStockinSku skuBean = new ReturnStockinSku();
			BeanUtils.copyProperties(returnStockinSkuVO, skuBean);
			returnStockinSkuDAOImpl.insertStockIn(skuBean);

			Integer qty = returnStockinSkuVO.getQty();

			// 更新库存数，残次品数
			StockVO stockVO = new StockVO();
			stockVO.setEntId(entId);
			stockVO.setSkuId(returnStockinSkuVO.getSkuId());
			stockVO.setStorId(returnStockinVO.getStorId());
			stockVO.setSourceCode(returnStockinVO.getSourceCode());
			stockVO.setTag("本地退货入库单");
			if ("zp".equals(returnStockinSkuVO.getInventoryType())) {
				stockVO.setStockQty(qty); // 库存数
			} else {
				stockVO.setJunkQty(qty); // 残次品数
			}
			stockService.updateStock(stockVO);

			// 加权成本价计算
			if (!"n".equals(sysReturnSku.get(0).getIsOrderSku())) {
				GoodsCostVO goodsCost = new GoodsCostVO();
				goodsCost.setSkuId(returnStockinSkuVO.getSkuId());
				goodsCost.setQty(qty);
				goodsCost.setOrigCost(returnStockinSkuVO.getGoodsSkuCost());
				goodsCost.setSourceId(returnStockinVO.getStockinId());
				goodsCost.setSourceCode(returnStockinVO.getSourceCode());
				goodsCost.setEntId(entId);
				goodsCost.setOperType("本地退货入库");
				goodsCost.setRemark("总库存数加上实际入库数小于等于零，加权平均值取商品规格原成本");
				adjustSkuService.DoGoodsCostComputer(goodsCost, currentUser.getFullName());
			}
		}

		return updateCount;
	}

    @Override
    public int getUnGoingCount(Map<String, String> paramMap) throws Exception {
        return returnStockinDAOImpl.getUnGoingCount(paramMap);
    }

	// /**
	// * 通过来源ID获取退货入库单信息 wangxing add
	// *
	// * @param strSourceId
	// * @return
	// * @throws Exception
	// */
	// public ReturnStockinVO getReturnStockInInfoBySourceId(String strSourceId)
	// throws Exception {
	// return ReturnStockinDAOImpl.getReturnStockInInfoBySourceId(strSourceId);
	// }

}
